package com.nj.dms.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nj.dms.dao.FileDao;
import com.nj.dms.dao.impl.FileDaoImpl;

/**
 * 下载文件
 */
@WebServlet("/DownloadFile")
public class DownloadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int id = new Integer(request.getParameter("id"));

		FileDao fileDao = new FileDaoImpl();
		String path = fileDao.getFilePath(id);

		String serPath = request.getServletContext().getRealPath("/") + "uploads" + File.separator + path;

		// 下载文件 - 2018-3-21 16:55:06
		File file = new File(serPath);

		// 创建文件输入流
		FileInputStream fis = new FileInputStream(file);

		// 创建服务器向客户端的输出流
		OutputStream out = response.getOutputStream();

		// 获取文件名称
		// substring(fileName.lastIndexOf("."), fileName.length())
		String fileName = path.substring(path.lastIndexOf(File.separator) + 1, path.length());

		// 设置响应头信息
		response.setHeader("Content-Disposition",
				"attachment;filename=\"" + new String(fileName.getBytes("utf-8"), "iso-8859-1") + "\"");

		// 将服务器上的输入流写入到客户端的输出流
		int temp = 0;
		while ((temp = fis.read()) != -1) {

			out.write(temp);

		}

		// 关闭输入流和输出流
		fis.close();
		out.close();

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
